import type { ApiResponse, GameItem } from '../types';
import { getAuthToken } from './auth';

// 基础API URL
// 注意：在实际项目中，可以通过环境变量配置API URL
const BASE_URL = 'http://localhost:8080/api/v1';

// 请求包装函数
async function request<T = any>(endpoint: string, options: RequestInit = {}): Promise<ApiResponse<T>> {
  const url = `${BASE_URL}${endpoint}`;
  
  // 默认选项
  const defaultOptions: RequestInit = {
    headers: {
      'Content-Type': 'application/json',
    },
    ...options,
  };

  // 添加认证token
  const token = getAuthToken();
  if (token && !options.headers?.hasOwnProperty('Authorization')) {
    (defaultOptions.headers as Record<string, string>)['Authorization'] = `Bearer ${token}`;
  }

  try {
    console.log('Making API request to:', url);
    console.log('Request options:', defaultOptions);
    
    const response = await fetch(url, defaultOptions);
    
    console.log('API response status:', response.status);
    console.log('API response headers:', response.headers);
    
    if (!response.ok) {
      throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
    }
    
    // 检查响应是否为空
    const contentType = response.headers.get('content-type');
    if (contentType && contentType.includes('application/json')) {
      const backendResponse = await response.json();
      // 将后端响应格式转换为前端期望的格式
      // 后端返回格式: { code: number, data: any, message: string }
      // 前端期望格式: { success: boolean, data: any, message: string }
      return {
        success: backendResponse.code === 0,
        data: backendResponse.data,
        message: backendResponse.message
      } as ApiResponse<T>;
    }
    
    const text = await response.text();
    return { success: true, data: text as unknown as T };
  } catch (error) {
    console.error(`请求 ${url} 失败:`, error);
    throw error;
  }
}

// 用户相关API
export const userAPI = {
  // 注册用户
  register: (username: string, password: string, nickname: string) => request('/user/register', {
    method: 'POST',
    body: JSON.stringify({ username, password, nickname }),
  }),
  
  // 用户登录
  login: (username: string, password: string) => request('/user/login', {
    method: 'POST',
    body: JSON.stringify({ username, password }),
  }),
  
  // 获取用户信息
  getUserInfo: () => request('/user/info', {
    method: 'GET',
    credentials: 'include', // 包含cookie
  }),
};

// 游戏相关API
export const gameAPI = {
  // 创建角色
  createCharacter: (characterName: string) => request('/game/character/create', {
    method: 'POST',
    body: JSON.stringify({ name: characterName }),
    credentials: 'include',
  }),
  
  // 获取角色信息
  getCharacterInfo: () => request('/game/character/info', {
    method: 'GET',
    credentials: 'include',
  }),
  
  // 打坐修炼
  meditate: () => request('/game/cultivate', {
    method: 'POST',
    credentials: 'include',
  }),
    
  // 探索秘境
  explore: () => request('/game/explore', {
    method: 'POST',
    credentials: 'include',
  }),
  
  // 炼丹制药
  alchemy: () => request('/game/alchemy', {
    method: 'POST',
    credentials: 'include',
  }),
  
  // 挑战心魔
  challengeDemon: () => request('/game/breakthrough', {
    method: 'POST',
    credentials: 'include',
  }),
  
  // 获取游戏状态
  getGameStatus: () => request('/game/status', {
    method: 'GET',
    credentials: 'include',
  }),
};

// 物品相关API
export const itemAPI = {
  // 获取物品列表
  getInventory: () => request<GameItem[]>('/game/inventory', {
    method: 'GET',
    credentials: 'include',
  }),
  
  // 使用物品
  useItem: (itemId: string) => request('/game/item/use', {
    method: 'POST',
    body: JSON.stringify({ itemId }),
    credentials: 'include',
  }),
};

export default { request, userAPI, gameAPI, itemAPI };